<script setup lang="tsx">
import { onMounted, ref } from 'vue';
import { NButton, NTag } from 'naive-ui';
import { fetchGetDeptTree, fetchGetUserList } from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { enableStatusRecord, genderRecord } from '@/constants/business';
import UserOperateModal from './modules/user-operate-modal.vue';
import UserDetailModal from './modules/user-detail-modal.vue';
import UserSearch from './modules/user-search.vue';

defineOptions({
  name: 'OrganizationManage'
});

const appStore = useAppStore();

// 部门树相关
const deptTreeData = ref<Api.SystemManage.DeptTree[]>([]);
const selectedDeptId = ref<number | null>(null);
const selectedDeptName = ref<string>('');
const expandedKeys = ref<number[]>([]);

// 用户表格相关
const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: fetchGetUserList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    deptId: null,
    userName: null,
    gender: null,
    nickName: null,
    telephone: null,
    email: null,
    status: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 48
    },
    {
      key: 'userName',
      title: $t('page.manage.user.userName'),
      align: 'center',
      minWidth: 100,
      width: 120
    },
    {
      key: 'nickName',
      title: $t('page.manage.user.nickName'),
      align: 'center',
      minWidth: 100,
      width: 120
    },
    {
      key: 'gender',
      title: $t('page.manage.user.gender'),
      align: 'center',
      width: 80,
      render: row => {
        if (row.gender === null) {
          return null;
        }

        const label = $t(genderRecord[row.gender]);
        const tagMap: Record<Api.SystemManage.gender, NaiveUI.ThemeColor> = {
          '1': 'primary',
          '0': 'error'
        };

        return <NTag type={tagMap[row.gender]}>{label}</NTag>;
      }
    },
    {
      key: 'telephone',
      title: $t('page.manage.user.telephone'),
      align: 'center',
      minWidth: 120,
      width: 140
    },
    {
      key: 'email',
      title: $t('page.manage.user.email'),
      align: 'center',
      minWidth: 150,
      width: 180
    },
    {
      key: 'status',
      title: $t('page.manage.user.status'),
      align: 'center',
      width: 80,
      render: row => {
        if (row.status === null) {
          return null;
        }

        const label = $t(enableStatusRecord[row.status]);
        const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
          1: 'success',
          2: 'warning'
        };

        return <NTag type={tagMap[row.status]}>{label}</NTag>;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="info" ghost size="small" onClick={() => showDetail(row.id)}>
            {$t('common.detail')}
          </NButton>

          <NButton type="primary" ghost size="small" onClick={() => handleEditUser(row.id)}>
            {$t('common.edit')}
          </NButton>

          <NButton type="error" ghost size="small" onClick={() => showDeleteConfirm(row.id)}>
            {$t('common.delete')}
          </NButton>
        </div>
      )
    }
  ]
});

const {
  modalVisible,
  operateType,
  editingData,
  modalFormData,
  checkedRowKeys,
  handleAdd,
  handleEdit,
  onBatchDeleted,
  onDeleted,
  onShowDetail
} = useTableOperate(data, getData);

// 用户操作模态框
const userOperateModalVisible = ref(false);
const userDetailModalVisible = ref(false);

// 获取部门树数据
async function getDeptTreeData() {
  const { error, data: treeData } = await fetchGetDeptTree();
  if (!error) {
    deptTreeData.value = treeData;
    // 默认展开第一级
    if (treeData.length > 0) {
      expandedKeys.value = treeData.map(item => item.id);
    }
  }
}

// 处理部门选择
function handleDeptSelect(keys: number[], option: any) {
  if (keys.length > 0) {
    selectedDeptId.value = keys[0];
    selectedDeptName.value = option[0]?.label || '';
    // 更新搜索参数并重新获取用户数据
    searchParams.deptId = selectedDeptId.value;
    getData();
  } else {
    selectedDeptId.value = null;
    selectedDeptName.value = '';
    searchParams.deptId = null;
    getData();
  }
}

// 构建树形选项
function buildTreeOptions(deptList: Api.SystemManage.DeptTree[]): any[] {
  return deptList.map(item => ({
    key: item.id,
    label: item.deptName,
    children: item.children && item.children.length > 0 ? buildTreeOptions(item.children) : undefined
  }));
}

// 用户操作相关函数
function handleAddUser() {
  handleAdd();
  userOperateModalVisible.value = true;
}

function handleEditUser(id: number) {
  const userData = data.value.find(item => item.id === id);
  if (userData) {
    editingData.value = userData;
    operateType.value = 'edit';
    userOperateModalVisible.value = true;
  }
}

function showDetail(id: number) {
  onShowDetail(id);
  userDetailModalVisible.value = true;
}

function showDeleteConfirm(id: number) {
  window.$dialog?.warning({
    title: $t('common.tip'),
    content: $t('common.confirmDelete'),
    positiveText: $t('common.confirm'),
    negativeText: $t('common.cancel'),
    onPositiveClick: () => {
      handleDelete(id);
    }
  });
}

function handleDelete(id: number) {
  // request

  onDeleted();
}

function handleBatchDelete() {
  // request

  onBatchDeleted();
}

function showBatchDeleteConfirm() {
  window.$dialog?.warning({
    title: $t('common.tip'),
    content: $t('common.confirmDelete'),
    positiveText: $t('common.confirm'),
    negativeText: $t('common.cancel'),
    onPositiveClick: () => {
      handleBatchDelete();
    }
  });
}

// 用户操作提交后的回调
function onUserOperateSubmitted() {
  userOperateModalVisible.value = false;
  getData();
}

// 页面初始化
onMounted(() => {
  getDeptTreeData();
  getData();
});
</script>

<template>
  <div class="min-h-500px flex gap-16px overflow-hidden lt-sm:overflow-auto">
    <!-- 左侧部门树 -->
    <div class="w-300px flex-shrink-0">
      <NCard :title="$t('page.manage.organization.deptTree')" :bordered="false" size="small" class="h-full">
        <template #header-extra>
          <NButton size="small" @click="getDeptTreeData">
            <template #icon>
              <icon-ic-round-refresh class="text-icon" />
            </template>
            {{ $t('common.refresh') }}
          </NButton>
        </template>

        <div class="h-600px overflow-auto">
          <NTree
            :data="buildTreeOptions(deptTreeData)"
            :expanded-keys="expandedKeys"
            selectable
            block-line
            @update:selected-keys="handleDeptSelect"
          />
        </div>
      </NCard>
    </div>

    <!-- 右侧用户信息 -->
    <div class="flex-col-stretch flex-1 gap-16px">
      <!-- 用户搜索 -->
      <UserSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getData" />

      <!-- 用户信息标题和操作 -->
      <NCard
        :title="
          selectedDeptName
            ? `${selectedDeptName} - ${$t('page.manage.organization.userList')}`
            : $t('page.manage.organization.allUsers')
        "
        :bordered="false"
        size="small"
        class="sm:flex-1-hidden card-wrapper"
      >
        <template #header-extra>
          <div class="flex gap-8px">
            <NButton size="small" type="primary" @click="handleAddUser">
              <template #icon>
                <icon-ic-round-plus class="text-icon" />
              </template>
              {{ $t('common.add') }}
            </NButton>
            <NButton
              size="small"
              ghost
              type="error"
              :disabled="checkedRowKeys.length === 0"
              @click="showBatchDeleteConfirm"
            >
              <template #icon>
                <icon-ic-round-delete class="text-icon" />
              </template>
              {{ $t('common.batchDelete') }}
            </NButton>
            <NButton size="small" ghost type="info" @click="getData">
              <template #icon>
                <icon-ic-round-refresh class="text-icon" />
              </template>
              {{ $t('common.refresh') }}
            </NButton>
          </div>
        </template>

        <NDataTable
          v-model:checked-row-keys="checkedRowKeys"
          :columns="columns"
          :data="data"
          size="small"
          :flex-height="!appStore.isMobile"
          :scroll-x="962"
          :loading="loading"
          remote
          :row-key="row => row.id"
          :single-line="false"
          :pagination="mobilePagination"
          class="sm:h-full"
        />
      </NCard>
    </div>

    <!-- 用户操作模态框 -->
    <UserOperateModal
      v-model:visible="userOperateModalVisible"
      :operate-type="operateType"
      :row-data="editingData"
      :selected-dept-id="selectedDeptId"
      @submitted="onUserOperateSubmitted"
    />

    <!-- 用户详情模态框 -->
    <UserDetailModal v-model:visible="userDetailModalVisible" :row-data="modalFormData" />
  </div>
</template>

<style scoped>
.card-wrapper {
  @apply overflow-hidden;
}
</style>
